package com.example.news.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.news.mapper.NewsMapper;
import com.example.news.mapper.NewsTypeMapper;
import com.example.news.pojo.News;
import com.example.news.pojo.NewsType;
import com.example.news.pojo.Result;
import com.example.news.service.NewsTypeService;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class NewsTypeServiceImpl extends ServiceImpl<NewsTypeMapper, NewsType> implements NewsTypeService {

    @Autowired
    private NewsTypeMapper newsTypeMapper;

    @Autowired
    private NewsMapper newsMapper;

    public Page<NewsType> searchPageType(News news, Integer pageNum, Integer pageSize) {
        String newsName = news.getNewsName();
        //创建分页对象
        Page<NewsType> page = new Page<>(pageNum, pageSize);
        //执行分页查询
        QueryWrapper<NewsType> queryWrapper = new QueryWrapper<>();
        if (newsName != null && !newsName.isEmpty()) {
            queryWrapper.like("type_name", newsName);
        }
        //执行查询
        Page<NewsType> resultPage = newsTypeMapper.selectPage(page, queryWrapper);
        //返回结果
        return resultPage;

    }

    @Override
    public void saveNewType(NewsType newsType) {
        if (newsType.getTypeName() == null){
            newsType.setTypeName(newsType.getTypeName());
        }
        if (newsType.getParentId() == null) {
            newsType.setParentId(0L);
        }
        newsTypeMapper.insert(newsType);
    }

    @Override
    public void removeNewTypeByIds(List<Long> ids) {
        //如果该类型下有子类型，则不能删除
        for (Long id : ids) {
            LambdaQueryWrapper<News> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(News::getNewsTypeId, id);
            List<News> newsTypes = newsMapper.selectList(queryWrapper);
            if (newsTypes.size() > 0) {
                throw new RuntimeException("该类型下有子类型，不能删除");
            }
        }
        newsTypeMapper.deleteBatchIds(ids);
    }

}
